<script lang="ts" setup>
import type { ConfigItem } from './types'; // 定义配置项的类型

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { Button, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { formatValues, generateFormSchema } from '#/utils';

import DataFormModalView from './DataFormModal.vue';

const props = defineProps<{
  fetchConfig: (
    id: string,
    params?: any,
  ) => Promise<{ config: Record<string, ConfigItem> }>;
  isExtra?: boolean;
  onSubmit: (values: {
    fields?: any;
    id?: string;
    values: Record<string, any>;
  }) => Promise<void>;
}>();

const pluginId = ref();
const extraFields: any[] = [];
const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  showDefaultActions: false,
  // 提交函数
  handleSubmit: (values) => {
    const formApiState = formApi.getState();
    const formApiStateSchema = formApiState?.schema || [];

    const newValues = formatValues(formApiStateSchema, values);
    props.onSubmit({
      values: newValues,
      fields: extraFields,
      id: pluginId.value,
    });
  },
});
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onClosed() {
    formApi.setState({ schema: [] });
  },
  onCancel() {
    formModalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;

    const modalData: any = formModalApi.getData();
    if (modalData) {
      pluginId.value = modalData.id;
      try {
        const { config } = await props.fetchConfig(
          modalData.id,
          modalData?.params ?? null,
        );
        const { schema, values } = generateFormSchema(config);

        formApi.setState({ schema });
        formApi.setValues(values);
      } catch (error) {
        console.error('加载配置失败', error);
        message.error('加载配置失败，请重试');
      }
    }
  },
});

const [AddModal, AddModalApi] = useVbenModal({
  connectedComponent: DataFormModalView,
  fullscreenButton: false,
  async onClosed() {
    const data = AddModalApi.getData();
    if (data) {
      const field = cloneDeep(data);
      const config: any = [field];
      const formSchema = generateFormSchema(config);
      formApi.setState((prev) => {
        const isSome = prev?.schema?.some(
          (item) => item.fieldName === formSchema.schema[0].fieldName,
        );
        if (isSome) {
          message.info('存在相同字段！');
          return {
            schema: [...(prev?.schema ?? [])],
          };
        }
        extraFields.push(field);
        return {
          schema: [...(prev?.schema ?? []), formSchema.schema[0]],
        };
      });
    }
  },
});

const handleAdd = () => {
  AddModalApi.setState({
    title: '添加字段',
  });
  AddModalApi.open();
};
</script>

<template>
  <Modal>
    <AddModal />
    <Form />
    <Button v-if="isExtra" type="primary" @click="handleAdd">新增字段</Button>
  </Modal>
</template>
